# Enemy.gd
extends CharacterBody2D

@export var move_speed = 75.0 # 敌人移动速度
@export var max_health = 100 # 最大生命值
@export var damage_to_player = 10 # 每次碰撞玩家造成的伤害

var current_health = max_health # 当前生命值

@onready var sprite: Sprite2D = $Sprite2D # 确保你的Sprite2D节点名称是Sprite2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var health_bar: ProgressBar = $ProgressBar

# 用于在_physics_process中获取玩家引用
var player: CharacterBody2D = null

func _ready():
	current_health = max_health
	update_health_bar()
	
	# 寻找场景中的玩家节点
	# 通常玩家是唯一的，你可以通过其名称或组来获取
	# 假设玩家的节点名称是 "Player"
	player = get_tree().get_first_node_in_group("友方") # 推荐使用组来获取
	if player == null:
		printerr("玩家节点未找到！请确保玩家节点在 '友方' 组中。")

	# 初始化闪烁动画
	#create_flicker_animation()

func _physics_process(delta: float):
	if player == null || !is_instance_valid(player):
		# 如果玩家不存在或已被销毁，敌人停止移动
		velocity = Vector2.ZERO
		move_and_slide()
		return

	# 计算朝向玩家的方向
	var direction_to_player = (player.global_position - global_position).normalized()

	# 设置速度并移动
	velocity = direction_to_player * move_speed
	move_and_slide()

	# (可选) 让敌人Sprite朝向移动方向
	if velocity.x != 0:
		sprite.flip_h = velocity.x < 0 # 根据X轴速度翻转Sprite

	# 检查是否与玩家发生碰撞
	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		var collider = collision.get_collider()
		if collider == player:
			# 敌人与玩家发生碰撞
			if player.has_method("take_damage"):
				player.take_damage(damage_to_player)
				# 造成伤害后，可以短暂停止移动，或者反弹
				# velocity = -direction_to_player * move_speed * 0.5 # 简单反弹
				# 或者，为了避免持续伤害，可以设置一个伤害冷却时间

func take_damage(amount: int):
	current_health -= amount
	current_health = clampi(current_health, 0, max_health) # 确保血量不超限
	update_health_bar()
	print(name, " 受到 ", amount, " 点伤害，剩余血量：", current_health)

	# 播放闪烁动画
	animation_player.play("flicker")

	if current_health <= 0:
		die()

func update_health_bar():
	if health_bar:
		health_bar.value = current_health


func die():
	print(name, " 死亡！")
	global.ex+=1
	# 播放死亡动画、音效等
	# 例如：播放一个死亡粒子效果
	# ...
	queue_free() # 销毁敌人节点
